import { NestFactory } from '@nestjs/core'
import { AppModule } from './app.module'
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'
import { ResponseInterceptor } from './common/interceptor/response.interceptor'
import { HttpExceptionFilter } from './common/filter/http-exception.filter'
import { ValidationExceptionFilter } from './common/filter/validation.filter'
import { ValidationPipe } from '@nestjs/common'
import cookieParser from 'cookie-parser'
import { PrismaExceptionFilter } from './common/filter/prisma-exception.filter'

async function bootstrap() {
  // 创建nestjs应用实例
  const app = await NestFactory.create(AppModule)

  // 获取日志服务
  const logger = app.get('WINSTON_LOGGER')

  // 先使用cookieParser中间件
  app.use(cookieParser())

  // 使用cors包作为中间件配置CORS
  app.enableCors({
    origin: ['http://127.0.0.1:5500', 'http://localhost:5500'],
    credentials: true,
  })

  // 配置 Swagger
  const config = new DocumentBuilder()
    .setTitle('NestJS API 示例')
    .setDescription('NestJS API 接口文档')
    .setVersion('1.0')
    .addTag('用户管理')
    .addTag('首页')
    .build()

  const document = SwaggerModule.createDocument(app, config)
  SwaggerModule.setup('api', app, document)

  // 配置全局验证管道
  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
      whitelist: true,
      forbidNonWhitelisted: true,
    }),
  )

  // 注册全局响应拦截器
  app.useGlobalInterceptors(new ResponseInterceptor(logger))

  // 注册全局异常过滤器，注意顺序很重要
  app.useGlobalFilters(
    new ValidationExceptionFilter(),
    new HttpExceptionFilter(logger),
    new PrismaExceptionFilter(),
  )

  await app.listen(process.env.PORT ?? 3000)
  logger.log(`应用已启动在: http://localhost:${process.env.PORT || 3000}`)
}

bootstrap().catch(console.error)
